package com.edu.policy.data.netty;

import com.edu.policy.data.domain.ModbusData;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
@Log4j2
public class DataBuffer {
    private static final int BATCH_SIZE = 2; // 批量插入的阈值
    private final List<ModbusData> buffer = new ArrayList<>();
    private final HikariDataSource tdengineDataSource;

    // 添加数据到缓存
    public void add(ModbusData data) {
        buffer.add(data);
        if (buffer.size() >= BATCH_SIZE) {
            flush(); // 触发批量插入
        }
    }

    // 批量插入数据
    public void flush() {
        if (buffer.isEmpty()) {
            return;
        }
        // 生成批量插入 SQL
        String sql = generateBatchInsertSQL(buffer);
        // 执行 SQL
        executeBatchInsert(sql);
        // 清空缓存
        buffer.clear();
    }

    // 生成批量插入 SQL
    private String generateBatchInsertSQL(List<ModbusData> dataList) {
        StringBuilder sqlBuilder = new StringBuilder();
        String deviceId = dataList.getFirst().getDeviceId(); // 假设同一批数据的设备 ID 相同
        String deviceName = "中冶设备" + deviceId; // 设备名称

        sqlBuilder.append("INSERT INTO device_")
                .append(deviceId)
                .append(" USING modbus_raw_data TAGS ('")
                .append(deviceName)
                .append("') VALUES ");

        for (int i = 0; i < dataList.size(); i++) {
            ModbusData data = dataList.get(i);
            sqlBuilder.append(String.format("(%d, '%s', %d, '%s')",
                    data.getTimestamp(), // 时间戳
                    data.getDeviceId(), // 设备 ID
                    data.getFunctionCode(), // 功能码
                    data.getRawData() // 原始数据
            ));
            if (i < dataList.size() - 1) {
                sqlBuilder.append(", ");
            }
        }
        return sqlBuilder.toString();
    }

    // 执行批量插入
    private void executeBatchInsert(String sql) {
        try (Connection conn = tdengineDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.execute();
            System.out.println("批量插入成功: " + sql);
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
    }
}
